"use client"

import type React from "react"

// First, let's import the necessary functions from api-client.ts
import { followUser, unfollowUser } from "@/lib/api-client"
import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { cn } from "@/lib/utils"
import { UserPlus, Check } from "lucide-react"
import {Artist} from "@/types";



interface ArtistCardProps {
  artist: Artist
  className?: string
  userId?: string
}

export function ArtistCard({ artist, className, userId }: ArtistCardProps) {
  const [isFollowing, setIsFollowing] = useState(artist.isFollowed || false)
  const [isLoading, setIsLoading] = useState(false)
  const [followerCount, setFollowerCount] = useState(artist.followerCount || 0)

  const handleFollowToggle = async (e: React.MouseEvent) => {
    e.preventDefault() // Prevent navigation to artist page
    e.stopPropagation() // Stop event propagation

    if (!userId) {
      // Redirect to login if no user ID
      window.location.href = "/login"
      return
    }

    setIsLoading(true)

    try {
      if (isFollowing) {
        await unfollowUser(userId,artist.id,2)
        setFollowerCount((prev) => Math.max(0, prev - 1))
      } else {
        await followUser(userId,artist.id,2)
        setFollowerCount((prev) => prev + 1)
      }

      setIsFollowing(!isFollowing)
    } catch (error) {
      console.error("关注/取消关注操作失败:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const formatFollowerCount = (count: number): string => {
    if (count >= 100000000) {
      return `${(count / 100000000).toFixed(1)}亿`
    } else if (count >= 10000) {
      return `${(count / 10000).toFixed(1)}万`
    } else if (count >= 1000) {
      return `${(count / 1000).toFixed(1)}千`
    } else {
      return count.toString()
    }
  }

  return (
      <div className={cn("group flex flex-col items-center gap-2", className)}>
        <Link href={`/artist/${artist.id}`} className="relative">
          <div className="relative w-40 h-40 overflow-hidden rounded-full">
            <Image
                src={artist.avatar || "/placeholder.svg?height=160&width=160"}
                alt={artist.name}
                fill
                className="object-cover transition-transform group-hover:scale-105"
            />
          </div>

          {/* Follow/Unfollow Button */}
          <button
              onClick={handleFollowToggle}
              disabled={isLoading}
              className={cn(
                  "absolute bottom-0 right-0 flex items-center gap-1 px-3 py-1.5 rounded-full text-sm font-medium transition-colors",
                  isFollowing
                      ? "bg-primary text-primary-foreground hover:bg-primary/90"
                      : "bg-gray-900 text-white hover:bg-gray-800",
                  isLoading && "opacity-70 cursor-not-allowed",
              )}
          >
            {isFollowing ? (
                <>
                  <Check className="h-4 w-4" />
                  <span>已关注</span>
                </>
            ) : (
                <>
                  <UserPlus className="h-4 w-4" />
                  <span>关注</span>
                </>
            )}
          </button>
        </Link>

        <div className="text-center">
          <h3 className="font-medium group-hover:text-primary transition-colors">{artist.name}</h3>
          <p className="text-sm text-muted-foreground">{formatFollowerCount(followerCount)} 粉丝</p>
        </div>
      </div>
  )
}

